package com.saltedfish.tool.util;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.saltedfish.tool.constant.StringConstant;
import com.saltedfish.tool.constant.StringConstant;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;

public class FileSizeUtil {
    public static final int SIZETYPE_B = 1;// 获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;// 获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;// 获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;// 获取文件大小单位为GB的double值
    private static final long DATE_ONE_WEEK = 14l * 24 * 60 * 60 * 1000;  //两周的时间

    /**
     * 获取文件指定文件的指定单位的大小
     *
     * @param filePath 文件路径
     * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
     * @return double值的大小
     */
    public static double getFileOrFilesSize(String filePath, int sizeType) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小", "获取失败!" + e.getMessage());
        }
        return FormetFileSize(blockSize, sizeType);
    }

    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static String getAutoFileOrFilesSize(String filePath) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取文件大小", "获取失败!");
        }
        return FormetFileSize(blockSize);
    }

    /**
     * 获取指定文件大小
     *
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    private static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df
                        .format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }


    /**
     * @param fileAbsPath
     * @return
     */
    public static boolean isFileExists(String fileAbsPath) {
        if (TextUtils.isEmpty(fileAbsPath))
            return false;
        File path = new File(fileAbsPath);
        return path.exists();
    }


    public static boolean deleteFiles(File file) {
        boolean delete = false;
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                delete =  file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                    delete = deleteFiles(files[i]); // 把每个文件 用这个方法进行迭代
                }
            }
//            delete = file.delete();
        } else {
            //   Constants.Logdada("文件不存在！"+"\n");
        }
        return  delete;
    }


    /**
     * 根据路径删除指定的目录或文件，无论存在与否
     *
     * @param
     * @return 删除成功返回 true，否则返回 false。
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {

        } else {
            if (file.isFile() && file.exists()) {
                // 为文件时调用删除文件方法
                boolean delete = file.delete();
                return  delete;
            }
        }
        return  true;

    }


    /**
     * 读取照片exif信息中的旋转角度
     *
     * @param path
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    /**
     * 那么我们只需要根据旋转角度将图片旋转过来就OK了
     *
     * @param img
     * @return
     */
    public static Bitmap toturn(Bitmap img, int rotate) {
        Matrix matrix = new Matrix();
        matrix.postRotate(+rotate); /*翻转90度*/
        int width = img.getWidth();
        int height = img.getHeight();
        img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
        return img;
    }

    /**
     * 删除超过时间的日志
     */
    public static void deletePostLog() {
        long nowDate = new Date().getTime();
        long goneDate = nowDate;
        if ((SharePreferceUtils.getLong("CURRENT_TIME")) > 0) {
            goneDate = SharePreferceUtils.getLong("CURRENT_TIME");
        }else{
            SharePreferceUtils.saveLong("CURRENT_TIME", nowDate);
        }
        if ((nowDate - goneDate) >= 24 * 60 * 60 * 1000L||(nowDate - goneDate)==0) {
            try {


            File file = Environment.getExternalStorageDirectory();
            if (file.canWrite()) {
                file = new File(StringConstant.getLogDir());
                // FileSizeUtil.deleteFiles(file);

                if (file.exists()) { // 判断文件是否存在
                    if (file.isDirectory()) { // 否则如果它是一个目录
                        File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                        if (files.length != 0) {
                            for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                                // 把每个文件 用这个方法进行迭代
                                if (files[i].isFile()) {
                                    Date date = new Date(files[i].lastModified());
                                    if ((nowDate - date.getTime()) <= DATE_ONE_WEEK) {

                                    } else {
                                        boolean bool = files[i].delete();
                                    }

                                }
                            }
                        }


                    }
                }
            }
                SharePreferceUtils.saveLong("CURRENT_TIME", nowDate);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }


}
